package com.self.structure;

/**
 * 两个队列实现一个栈
 */
public class IStack {

    private int cap;

    private int size;

    // enqueue
    private NQueue queue_01;

    // dequeue
    private NQueue queue_02;

    public IStack(int cap) {
        this.cap = cap;
        this.queue_01 = new NQueue(cap);
        this.queue_02 = new NQueue(cap);
    }

    public void push(int el) {

        if(size == cap) {
            return;
        }

        if(queue_01.isEmpty()) {
            queue_02.push(el);
        } else {
            queue_01.push(el);
        }

        this.size++;
    }

    public int pop() {

        if(size <= 0) {
            throw new RuntimeException("IStack is empty");
        }

        int v;
        if(queue_01.isEmpty()) {
            transfer(queue_02,queue_01);
            v = queue_02.pop();
        } else {
            transfer(queue_01,queue_02);
            v = queue_01.pop();
        }

        this.size--;
        return v;
    }

    public boolean isEmpty() {
        return this.size <= 0;
    }

    private void transfer(NQueue from,NQueue to) {
        while (from.size() > 1) {
            to.push(from.pop());
        }
    }

    public static void main(String[] args) {

        IStack iStack = new IStack(5);
        for (int i = 0;i < 5;i++) {
            iStack.push(i);
        }

        while (!iStack.isEmpty()) {
            System.out.println(iStack.pop());
        }
    }
}
